local blaze = require "blaze"
local sort = table.sort

local M = {}

local function winner_sorter(a, b)
    if a.solved > b.solved then
        return true
    elseif a.solved < b.solved then
        return false
    end

    if a.cost < b.cost then
        return true
    elseif a.cost < b.cost then
        return false
    end

    if a.missed < b.missed then
        return true
    elseif a.missed > b.missed then
        return false
    end

    return false
end

local function sort_winner(players)
    sort(players, winner_sorter)
end

local function are_draw(players)
    local a = players[1]
    local b = players[2]
    if not a or not b then
        return false
    end
    return a.solved == b.solved and a.cost == b.cost and a.missed == b.missed
end

local function analyze_session(session, my_user_id)
    local status = session.status
    local state = session.state
    local players = state.players
    local me, target
    local win, lose, draw

    if players then
        for _, player in ipairs(players) do
            if player.user_id == my_user_id then
                me = player
            else
                target = player
            end
        end
    end

    if status == 0 then
        -- 未开始
    elseif status == 1 then
        -- 进行中
    elseif status == 2 then
        -- 已完成
        sort_winner(players)
        if are_draw(players) then
            draw = true
        elseif players[1] == me then
            win = true
        else
            lose = true
        end
    end

    return {
        win = win,
        lose = lose,
        draw = draw,
        me = me,
        target = target
    }
end

local function analyze(versus, my_user_id)
    local sessions = versus.sessions
    local me, target
    for _, player in ipairs(versus.players) do
        if player.user_id == my_user_id then
            me = player
        else
            target = player
        end
    end

    local win = 0
    local lose = 0
    local draw = 0
    local total = #sessions

    for _, session in ipairs(sessions) do
        local result = analyze_session(session, my_user_id)
        if result.win then
            win = win + 1
        elseif result.lose then
            lose = lose + 1
        elseif result.draw then
            draw = draw + 1
        end
    end

    return {
        win = win,
        lose = lose,
        draw = draw,
        total = total,
        me = me,
        target = target
    }
end

M.analyze = analyze
M.analyze_session = analyze_session

return M